package br.com.mural.android;

import java.util.HashMap;

import br.com.mural.android.entidades.Usuario;
import br.com.mural.android.util.GerenteSessao;
import br.com.mural.android.webservice.UsuarioRest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class PrincipalActivity extends Activity implements Runnable{
	private final int DELAY = 3000;
	public static int usuario_id;
	GerenteSessao session;
	Usuario usuario = new Usuario();
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_principal);
		Handler handler = new Handler();
		handler.postDelayed(this, DELAY);	
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.principal, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void run() {
		session = new GerenteSessao(getApplicationContext());
		session.checkLogin();

		HashMap<String, String> user = session.getUserDetails();

		String login = user.get(GerenteSessao.KEY_LOGIN);
		String senha = user.get(GerenteSessao.KEY_SENHA);
		Toast.makeText(this.getApplicationContext(), "Login:"+login + " - Senha: "+senha, Toast.LENGTH_SHORT).show();

		usuario = autentica(login, senha);
		
		Intent i;
		if (usuario != null) {
			usuario_id = usuario.getId();
			Toast.makeText(this.getApplicationContext(), "Usuario:"+usuario.getNome(), Toast.LENGTH_SHORT).show();
			i = new Intent(getApplicationContext(), MainAdminActivity.class);
		} else {
			i = new Intent(getApplicationContext(), MainActivity.class);
		}
		
		startActivity(i);
		finish();

	}

	private Usuario autentica(String login, String senha) {
		UsuarioRest usuarioRest = new UsuarioRest();
		try {
			usuario = usuarioRest.login(login, senha);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return usuario;
	}
}
